<script setup lang="ts">
import APIStoreHome from '~/api/store-home/index'
import type { ShopInfoResult } from '~/api/store-home/types'
import DialogMessage from '~/components/DialogMessage/index.vue'
import Search from '~/components/Search/index.vue'
import SelfPagination from '~/components/SelfPagination/index.vue'
import ItemMusic from '~/components/ItemMusic/index.vue'
import ItemFont from '~/components/ItemFont/index.vue'
import Filtrate from '~/components/Filtrate/index.vue'
import { useAuth } from '~/stores/auth/index'
import { ElMessageBox, ElLoading, ElMessage } from 'element-plus'
import ItemVideoSample from '~/components/ItemVideoSample/index.vue'
import { urlToFile, replaceCommaWithDash } from '~/utils/index'
import { ArrowDownBold } from '@element-plus/icons-vue'

definePageMeta({
    showSmallSearchBox: true
})

interface Props {
    image?: string;
    sample?: string;
}

const { info: selfInfo, token } = storeToRefs(useAuth())

const $route = useRoute()
const activeName = shallowRef<any>('')

const queryParams = ref<PageQuery>({
    page: 1,
    limit: 8
})
const loading = shallowRef<boolean>(false)



const info = ref<ShopInfoResult>({})

const tabPane = reactive([{
    id: 5,
    label: '搬运-视频',
    value: 'trans_video'
}, {
    id: 6,
    label: '收藏夹-视频',
    value: 'collection_video'
}])

async function getShopInfo() {
    if (token.value) {
        const { data } = await APIStoreHome.getLoginShopInfo(($route.query.shopId as string))
        info.value = data

    } else {
        const { data } = await APIStoreHome.getShopInfo(($route.query.shopId as string))
        info.value = data
    }

    if (info.value.is_video == 1) {
        activeName.value = 'video'
    } else if (info.value.is_picture == 1) {
        activeName.value = 'picture'
    } else if (info.value.is_music == 1) {
        activeName.value = 'music'
    } else if (info.value.is_font == 1) {
        activeName.value = 'font'
    }
}


function handleChangePaneTrans(type: string, text: string) {
    tabPane.splice(0, 1, { id: 5, label: `搬运-${text}`, value: `trans_${type}` })
    activeName.value = `trans_${type}`
}

function handleChangePaneCollection(type: string, text: string) {
    tabPane.splice(1, 1, { id: 6, label: `收藏夹-${text}`, value: `collection_${type}` })
    activeName.value = `collection_${type}`
}
const shopGoodsData = ref<any>({})
const list = ref<any[]>([])

watch(activeName, (newValue) => {
    shopGoodsData.value = {}
    getShopGoods()
    getConditionSelect(newValue)
})

const total = shallowRef<number>(0)

function getShopGoods() {
    loading.value = true
    list.value = []
    shopGoodsData.value.shop_id = ($route.query.shopId as string)
    shopGoodsData.value.type = activeName.value
    APIStoreHome.getShopGoods(shopGoodsData.value, queryParams.value).then(({ data, total: count }) => {
        list.value = data
        if (activeName.value == 'picture') {
            list.value.forEach(async (item: any) => {
                const url = await urlToFile(item.image, item.image)
                item.image = url
            })
        }
        total.value = count
    }).finally(() => {
        loading.value = false
    })
}

const columns = ref<any>([])

function onSelectChange(value: Ref) {
    const filter: any = {}
    const op: any = {}

    for (let item in value.value) {
        filter[item] = JSON.parse(value.value[item]).type
        op[item] = JSON.parse(value.value[item]).op
    }
    shopGoodsData.value.filter = JSON.stringify(filter)
    shopGoodsData.value.op = JSON.stringify(op)
    getShopGoods()
}

function getConditionSelect(type: any) {
    APIStoreHome.getConditionSelect(type).then(({ data }) => {
        columns.value = []
        if (type.includes('video')) {
            columns.value = [{
                placeholder: '类型',
                value: 'category_id',
                item: []
            }, {
                placeholder: '横竖屏',
                value: 'hv_screens',
                item: []
            }, {
                placeholder: '分辨率',
                value: 'resolving_power',
                item: []
            }, {
                placeholder: '时长',
                value: 'duration',
                item: []
            }, {
                placeholder: '格式',
                value: 'format',
                item: []
            }]
            columns.value[0].item = data.category_id
            columns.value[1].item = data.hv_screens
            columns.value[2].item = data.resolving_power
            columns.value[3].item = data.duration
            columns.value[4].item = data.format
        } else if (type.includes('picture')) {
            columns.value = [{
                placeholder: '横竖屏',
                value: 'hv_screens',
                item: []
            }, {
                placeholder: '格式',
                value: 'format',
                item: []
            }, {
                placeholder: '分辨率',
                value: 'dpi',
                item: []
            }]
            columns.value[0].item = data.hv_screens
            columns.value[1].item = data.format
            columns.value[2].item = data.dpi
        } else if (type.includes('music')) {
            columns.value = [{
                placeholder: '曲风',
                value: 'genre',
                item: []
            }, {
                placeholder: '情绪',
                value: 'emotion',
                item: []
            }, {
                placeholder: '乐器',
                value: 'musical',
                item: []
            }, {
                placeholder: '节拍',
                value: 'beat',
                item: []
            }, {
                placeholder: '时长',
                value: 'duration',
                item: []
            }]
            columns.value[0].item = data.genre
            columns.value[1].item = data.emotion
            columns.value[2].item = data.musical
            columns.value[3].item = data.beat
            columns.value[4].item = data.duration
        } else if (type.includes('font')) {
            columns.value = [{
                placeholder: '类型',
                value: 'font_type',
                item: []
            }, {
                placeholder: '风格',
                value: 'font_style',
                item: []
            }, {
                placeholder: '语系',
                value: 'language',
                item: []
            }, {
                placeholder: '格式',
                value: 'format',
                item: []
            }, {
                placeholder: '编码',
                value: 'font_code',
                item: []
            }]
            columns.value[0].item = data.font_type
            columns.value[1].item = data.font_style
            columns.value[2].item = data.language
            columns.value[3].item = data.format
            columns.value[4].item = data.font_code
        }
    })
}

const dialogVisible = shallowRef<boolean>(false)

const shopInfo = ref<any>({})

function handleShowDialogMessage() {
    shopInfo.value = {
        shop_id: $route.query.shopId,
        user_id: info.value.user_id,
        user: {
            head_img: info.value.head_img,
            username: info.value.username
        }
    }
    dialogVisible.value = true
}

function submitAttention() {
    ElMessageBox.confirm(
        '是否关注该店铺？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (!info?.value.Invite_code) return
        const loading = ElLoading.service({ lock: true })
        APIStoreHome.setUserConcern(info?.value.Invite_code).then(() => {
            getShopInfo()
        }).finally(() => {
            loading.close()
        })
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

function submitUnfollow() {
    ElMessageBox.confirm(
        '是否取消关注该店铺？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (!info?.value.Invite_code) return
        const loading = ElLoading.service({ lock: true })
        APIStoreHome.cancelUserConcern(info?.value.Invite_code).then(() => {
            getShopInfo()
        }).finally(() => {
            loading.close()
        })
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

const $router = useRouter()

function handleJumpVideoView(item: any) {
    $router.push({
        path: `/video-details/${item.id}`,
        query: {
            categoryType: `Video${item.transport_id ? `&transport_id=${item.transport_id}` : ''}`
        }
    })
}

function handleJumpPictureView(id: number) {
    $router.push({
        path: `/picture-details/${id}`,
        query: {
            categoryType: 'Picture'
        }
    })
}

const value = shallowRef<string>('')

function handleSearch() {
    shopGoodsData.value.keyword = value.value
    getShopGoods()
}

const fdas = shallowRef<boolean>(false)

onMounted(() => {
    fdas.value = true
    getShopInfo()
})

</script>

<template>
    <div class="store-home">
        <div class="title-info" v-if="info.background" :style="`background-image: url(${info.background});`">
            <div class="avatar">
                <img v-if="info.head_img" :src="info.head_img" alt="head_img">
            </div>
            <div class="name">
                <div>{{ info.username }}</div>
                <div>
                    <span v-if="info.user_type == 'personal'">{{ info?.auth_info?.real_name }}</span>
                    <span v-if="info.user_type == 'company'">{{ info?.auth_info?.company_name }}</span>
                    <span v-if="info.user_type == 'personal'">（个人）</span>
                    <span v-if="info.user_type == 'company'">（公司）</span>
                    <span v-if="info.user_type == 'personal'"> {{ info?.auth_info?.id_card }}</span>
                    <span v-if="info.user_type == 'company'"> {{ info?.auth_info?.registration_code }}</span>
                </div>
            </div>
            <div class="btns" v-if="info.Invite_code != selfInfo.Invite_code">
                <button @click="handleShowDialogMessage">私信</button>
                <button v-if="info.is_concern == 0" @click="submitAttention">+关注</button>
                <button v-else-if="info.is_concern == 1" type="button" style="background-color: #9499a0;"
                    @click="submitUnfollow">已关注</button>
            </div>
            <div class="location">
                <img src="./images/location.png" alt="location">
                <div>{{ replaceCommaWithDash(info.area) }}</div>
            </div>
            <div class="number">
                <div class="number-item">作品: {{ info.works }}</div>
                <div class="number-item">点赞: {{ info.likes }}</div>
                <div class="number-item">收藏: {{ info.collections }}</div>
                <div class="number-item">转发: {{ info.shares }}</div>
                <div class="number-item">最近收益: {{ info.income }}</div>
            </div>
            <div class="introduce">
                {{ info.brief }}
            </div>
        </div>
        <div class="store-home-content">
            <Search v-model="value" class="tabs-search" @on-btn-click="handleSearch" />
            <el-tabs v-model="activeName" class="tabs" v-if="fdas">
                <el-tab-pane name="video" v-if="info.is_video == 1"><template
                        #label><span>视频</span></template></el-tab-pane>
                <el-tab-pane name="picture" v-if="info.is_picture == 1"><template
                        #label><span>图片</span></template></el-tab-pane>
                <el-tab-pane name="music" v-if="info.is_music == 1"><template
                        #label><span>音乐</span></template></el-tab-pane>
                <el-tab-pane name="font" v-if="info.is_font == 1"><template
                        #label><span>字体</span></template></el-tab-pane>
                <el-tab-pane v-for="(item, index) in tabPane" :key="item.id" :label="item.label" :name="item.value">
                    <template #label>
                        <el-dropdown v-if="item.value.includes('trans')">
                            <span class="tab-item" :class="{ 'tab-item-active': activeName.includes('trans') }">
                                {{ item.label }}
                                <el-icon :size="12" color="rgb(96, 98, 102)" style="margin-left: 5px;">
                                    <ArrowDownBold />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        @click="handleChangePaneTrans('video', '视频')">搬运-视频</el-dropdown-item>
                                    <el-dropdown-item
                                        @click="handleChangePaneTrans('picture', '图片')">搬运-图片</el-dropdown-item>
                                    <el-dropdown-item
                                        @click="handleChangePaneTrans('music', '音乐')">搬运-音乐</el-dropdown-item>
                                    <el-dropdown-item
                                        @click="handleChangePaneTrans('font', '字体')">搬运-字体</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <el-dropdown v-else-if="item.value.includes('collection')">
                            <span class="tab-item" :class="{ 'tab-item-active': activeName.includes('collection') }">
                                {{ item.label }}
                                <el-icon :size="12" color="rgb(96, 98, 102)" style="margin-left: 5px;">
                                    <ArrowDownBold />
                                </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        @click="handleChangePaneCollection('video', '视频')">收藏夹-视频</el-dropdown-item>
                                    <el-dropdown-item
                                        @click="handleChangePaneCollection('picture', '图片')">收藏夹-图片</el-dropdown-item>
                                    <el-dropdown-item
                                        @click="handleChangePaneCollection('music', '音乐')">收藏夹-音乐</el-dropdown-item>
                                    <el-dropdown-item
                                        @click="handleChangePaneCollection('font', '字体')">收藏夹-字体</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <span v-else>{{ item.label }}</span>
                    </template>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="filtrate-search">
            <div class="filtrate-search-title">
                <div v-if="activeName.includes('video')" style="display: flex;">
                    视频个数：<span>{{ total }}</span>个视频
                </div>
                <div v-if="activeName.includes('picture')" style="display: flex;">
                    图片个数：<span>{{ total }}</span>个图片
                </div>
                <div v-if="activeName.includes('music')" style="display: flex;">
                    音乐个数：<span>{{ total }}</span>个音乐
                </div>
                <div v-if="activeName.includes('font')" style="display: flex;">
                    字体个数：<span>{{ total }}</span>个字体
                </div>
            </div>
            <Filtrate v-if="activeName.includes('video')" style="margin-left: 30px;" :columns="columns"
                @onSelectChange="onSelectChange" />
            <Filtrate v-if="activeName.includes('picture')" style="margin-left: 30px;" :columns="columns"
                @onSelectChange="onSelectChange" />
            <Filtrate v-if="activeName.includes('music')" style="margin-left: 30px;" :columns="columns"
                @onSelectChange="onSelectChange" />
            <Filtrate v-if="activeName.includes('font')" style="margin-left: 30px;" :columns="columns"
                @onSelectChange="onSelectChange" />
        </div>
        <div v-loading="loading">
            <el-empty description="暂无内容" v-if="!list || list?.length == 0" />
            <div v-if="activeName.includes('video')" class="list">
                <div class="item" v-for="item in list" :key="item" @click="handleJumpVideoView(item)">
                    <div class="frame">
                        <ItemVideoSample class="frame-item" :image="item.image" :sample="item.sample" />
                        <div class="frame-item" :style="{ backgroundImage: `url('${item.sprite}')` }"></div>
                    </div>
                </div>
            </div>
            <div v-if="activeName.includes('picture')" class="list-picture">
                <div class="list-picture-item" v-for="item in list" :key="item.id"
                    @click="handleJumpPictureView(item.id)">
                    <img :src="item.image" alt="image">
                </div>
            </div>
            <div v-if="activeName.includes('music')" class="list-music">
                <ItemMusic v-for="item in list" :key="item.id" :item="item" />
            </div>
            <div v-if="activeName.includes('font')" class="font-music">
                <ItemFont v-for="item in list" :key="item.id" :item="item" />
            </div>
        </div>
        <SelfPagination style="margin-top: 50px;margin-right: 30px;" :total="total"
            v-model:current-page="queryParams.page" :page-size="queryParams.limit" @get-list="getShopGoods" />
        <DialogMessage v-model="dialogVisible" :shopInfo="shopInfo" />
    </div>
</template>

<style lang="less" scoped>
.store-home {
    padding-bottom: 20px;

    .font-music {
        width: 1260px;
        margin: 0 auto;
    }

    .list-music {
        width: 1260px;
        margin: 0 auto;
    }

    .list-picture {
        width: 1260px;
        margin: 0 auto;
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin-bottom: 50px;

        &:after {
            content: '';
            display: block;
            flex-grow: 99999;
        }

        .list-picture-item {
            flex-grow: 1;
            border-radius: 5px;
            overflow: hidden;
            cursor: pointer;

            img {
                display: block;
                min-width: 100%;
                height: 200px;
                object-fit: cover;
            }
        }
    }

    .filtrate-search {
        width: 1260px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        font-family: 'SOURCEHANSANSCN-EXTRALIGHT';

        .filtrate-search-title {
            color: rgba(187, 187, 187, 1);
            font-size: 14px;
            font-weight: 700;

            span {
                color: #F91414;
                font-weight: 700;
                font-family: 'SOURCEHANSANSCN-REGULAR';
            }
        }
    }

    .list {
        border-radius: 5px;
        position: relative;
        width: 1260px;
        margin: 0 auto;
        z-index: 5;
        grid-template-columns: repeat(4, 1fr);
        display: flex;
        flex-wrap: wrap;
        gap: 20px;

        .item {
            width: 300px;
            cursor: pointer;
            border-radius: 5px;
            overflow: hidden;

            .frame {
                background-color: red;
                height: 340px;

                .frame-item {
                    height: 170px;
                    background-color: #e8e8e8;
                    background-size: cover;
                    background-position: center;
                    position: relative;

                    .title {
                        position: absolute;
                        left: 20px;
                        bottom: 0;
                        height: 45px;
                        line-height: 45px;
                        font-size: 14px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        color: #ffffff;
                    }

                }
            }
        }
    }

    .store-home-content {
        position: relative;
        width: 1260px;
        margin: 0 auto;

        .tabs-search {
            position: absolute;
            right: 0;
            top: 5px;
            z-index: 99;
            width: 180px;
        }
    }

    .tabs {
        margin-top: 10px;


        .tab-item {
            outline: none;
            display: flex;
            align-items: center;

            &:hover {
                color: #F91414;
            }
        }

        .tab-item-active {
            color: #F91414;
        }

        &:deep(.el-tabs__nav-wrap) {
            &::after {
                background-color: transparent;
            }
        }

        &:deep(.el-tabs__item.is-active) {
            color: #F91414;
        }

        &:deep(.el-tabs__nav-scroll) {
            display: flex;
            justify-content: center;
        }

        &:deep(.el-tabs__active-bar) {
            background-color: #F91414;
        }

        &:deep(.el-tabs__item) {
            &:hover {
                color: #F91414;

            }
        }
    }

    .title-info {
        height: 478px;
        background-repeat: no-repeat;
        background-size: cover;
        background-position: center center;
        overflow: hidden;
        background-color: #eeeeee;
        font-family: 'SOURCEHANSANSCN-EXTRALIGHT';

        .introduce {
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            text-align: center;
            margin-top: 10px;
        }

        .number {
            display: flex;
            justify-content: center;
            margin-top: 12px;
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            gap: 0 20px;
        }

        .location {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0 14px;
            margin-top: 10px;

            img {
                width: 20px;
                height: 20px;
                display: block;
            }

            div {
                color: rgba(255, 255, 255, 1);
                font-size: 14px;
            }

        }

        .btns {
            display: flex;
            justify-content: center;
            gap: 0 20px;
            margin-top: 14px;

            button {
                width: 50px;
                height: 20px;
                display: block;
                line-height: 20px;
                border-radius: 5px;
                border: none;
                cursor: pointer;

                &:first-child {
                    background-color: rgba(238, 239, 240, 1);
                    color: rgba(187, 187, 187, 1);
                    font-size: 12px;
                }

                &:last-child {
                    background-color: rgba(249, 20, 20, 1);
                    color: rgba(255, 255, 255, 1);
                    font-size: 12px;
                }
            }
        }

        .name {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
            gap: 0 20px;

            div {
                &:first-child {
                    color: rgba(255, 255, 255, 1);
                    font-size: 18px;
                    font-weight: 700;
                    font-family: 'SOURCEHANSANSCN-REGULAR';
                }

                &:last-child {
                    color: rgba(255, 255, 255, 1);
                    font-size: 14px;
                }
            }
        }

        .avatar {
            width: 105px;
            height: 105px;
            margin: 0 auto;
            background-color: #eeeeee;
            border-radius: 50%;
            margin-top: 140px;

            img {
                width: 100%;
                height: 100%;
                border-radius: 50%;
            }
        }
    }
}
</style>
